const path = require('path');
const { log } = require('console');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const TagsPlugin = require('html-webpack-tags-plugin');

// 生产环境
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");


// 判断是否生产环境
const isProduction = log('mode: ', process.env.NODE_ENV) || process.env.NODE_ENV === 'production';

// 处理ts文件的loader
const tsHandler = {
    swc: ['swc-loader'],
    babel: [
        {
            loader: 'babel-loader',
            // 配置babel缓存，修改cacheIdentifier的值，可重置缓存
            options: { cacheDirectory: true, cacheCompression: false, cacheIdentifier: 'change me to reset cache' }
        },
        'ts-loader']
}

// 根据是否生产环境，处理css相关loader
function getStyleLoaders(isProduction, ...Loaders) {
    return [
        isProduction ? MiniCssExtractPlugin.loader : "style-loader",
        'css-loader',
        {
            loader: 'postcss-loader',
            options: {
                postcssOptions: {
                    // 需要配置browserslist指定浏览器
                    // autoprefixer只能识别浏览器范围：如"ie >= 11"。"ie 11"不识别
                    plugins: ['postcss-preset-env'],
                }
            }
        },
        ...Loaders
    ].filter(Boolean)
}

// 根据是否生产环境，实例化不同的插件
function handlePlugins(isProduction) {
    if (isProduction) {
        return [
            new MiniCssExtractPlugin({
                filename: "css/[name].css",
                chunkFilename: "css/[name].chunk.css",
            })
        ]
    } else {
        return []
    }
}

module.exports = (env) => ({
    mode: isProduction ? 'production' : 'development',
    entry: { fiexible: './src/js/flexible.js', main: './src/index.ts' },
    output: {
        path: path.resolve(__dirname, './calculator'),
        clean: true,
        filename: 'js/[name].js',
        chunkFilename: "js/[name].chunk.js", // 主入口文件分割出来的文件命名
   		assetModuleFilename: "media/[name].[hash][ext]", // 图片、字体等资源模块命名方式
    },
    devtool: isProduction ? false : 'cheap-module-source-map',
    plugins: [
        new HtmlWebpackPlugin({
            inject: 'body',
            template: path.resolve(__dirname, './public/index.html'),
            favicon: path.resolve(__dirname, './public/greater.svg')
        }),
        // new CopyPlugin({
        //     patterns: [
        //         {
        //             from: "src/js/*",
        //             to: "old/[name][ext]",
        //             globOptions: {
        //                 ignore: ['**/*/flexible.js']
        //             }
        //         },
        //     ],
        // }),
        // new TagsPlugin({
        //     scripts: [
        //         'old/classModel.js', 'old/compute.js',
        //         'old/itemRegister.js', 'old/instance.js',
        //         'old/routine.js', 'old/main.js'
        //     ],
        //     append: true
        // }),
        ...handlePlugins(isProduction)
    ],
    resolve: {
        extensions: ['.js', '.ts'],
        alias: {
            '@base': path.resolve(__dirname, './src/base')
        }
    },
    module: {
        rules: [
            {
                oneOf: [
                    {
                        test: /.css$/,
                        use: getStyleLoaders(isProduction)
                    },
                    {
                        test: /.ts$/,
                        exclude: /(node_modules)/,
                        use: tsHandler[env.tsHandleTool]
                    },
                    console.log(env.tsHandleTool) && false
                ].filter(Boolean)
            }

        ]
    },
    optimization: {
        minimize: isProduction, // 只有当minimize为true，才会执行minimizer
        minimizer: [
            // 在 webpack@5 中，你可以使用 `...` 语法来扩展现有的 minimizer（即 `terser-webpack-plugin`），将下一行取消注释
            `...`,
            new CssMinimizerPlugin(),
        ],
        splitChunks: {
            chunks: 'all',
            filename:'js/[name].chunk.js'
        }
    },
})